﻿/*
=======================================================
    GroupInfo【集团】
=======================================================
*/

namespace Services
{
    public interface IGroupInfoLogic : ILogic<GroupInfoModel, GroupInfoFilterModel>
    {
        int UpdateIsDelete(bool flag, params int[] ids);
        void ResetPassword(List<int> ids, string pwd);
    }


    public class GroupInfoLogic : BaseLogic<GroupInfoModel, GroupInfoFilterModel, GroupInfo, IGroupInfoRepository, IGroupInfoMapping, IGroupInfoService>, IGroupInfoLogic
    {
        private readonly ICreateCode _ICreateCode;

        private readonly IUserRepository _userRepository;
        private readonly IUserMapping _userMapping;

        public GroupInfoLogic(ICurrentUser currentUser, IGroupInfoRepository repository, IGroupInfoMapping mapping, IGroupInfoService service, ICreateCode iCreateCode,
            IUserRepository __IUserRepository, IUserMapping __IUserMapping)
            : base(currentUser, repository, mapping, service)
        {
            _ICreateCode = iCreateCode;

            _userRepository = __IUserRepository;
            _userMapping = __IUserMapping;
        }

        #region 启用/禁用  UpdateIsDelete
        public int UpdateIsDelete(bool flag, params int[] ids)
        {
            return _repository.UpdateIsDelete(flag, ids);
        }
        #endregion

        #region Insert
        public override GroupInfoModel Insert(GroupInfoModel model)
        {
            if (model.Code.IsEmpty())
            {
                model.Code = _ICreateCode.GetGroupInfoCode();
            }

            if (_ICreateCode.GroupInfoOrRegulatorCodeIsExists(model.Code))
            {
                throw new CustomException("编号已经存在，系统要求集团与监管部门的编号要唯一！");
            }

            int id = _repository.InsertGroupInfo(_mapping.Model2Entity(model), model.LoginName, model.LoginPassword);
            return GetByID(id);
        }
        #endregion

        #region 重置密码  ResetPassword
        public void ResetPassword(List<int> ids, string pwd)
        {
            _repository.ResetPassword(ids, pwd);
        }
        #endregion

        public override GroupInfoModel GetByID(int id)
        {
            var model = base.GetByID(id);

            var user = _userRepository.GetModel(_userMapping.FilterModel2Where(new UserFilterModel() { _GroupInfoID = id, _CreateUserNameEqual = "系统自动" }));
            if (user != null)
            {
                model.LoginName = user.LoginName;
            }

            return model;
        }
    }
}
